package com.sjy.framework.codemultiplex;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Component
public class GrrovyScriptEngine implements ScriptEngine {

    private static final String UTF_ENCODING = "UTF-8";
    private static Map<String ,Script> scriptCache = new ConcurrentHashMap<>();

    private GroovyShell groovyShell;

    @PostConstruct
    public void init(){
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader(this.getClass().getClassLoader());
        CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
        compilerConfiguration.setSourceEncoding(UTF_ENCODING);
        groovyShell = new GroovyShell(groovyClassLoader,compilerConfiguration);
    }

    @Override
    public <T> Object scriptEval(T bindings, String scriptContent) {
        try{
            Script script ;
            String cacheKey = DigestUtils.md5DigestAsHex(scriptContent.getBytes("UTF-8"));

            if(scriptCache.containsKey(cacheKey)){
                script = scriptCache.get(cacheKey);
                script.setBinding((Binding) bindings);
            }else{
                script = groovyShell.parse(scriptContent);
                script.setBinding((Binding) bindings);
                scriptCache.put(cacheKey,script);
            }
            return  script.run();
        }catch (Exception e){

        }
        return null;
    }
}
